package mbsl.util;

import java.lang.ref.SoftReference;
import java.util.HashMap;

/**
 * A simple cacher.
 * <p>
 * Note that this cache employs soft references, meaning that if the application
 * runs low on memory, unused objects stored here might get released by the GC.
 * If that is the case, the get(int) method will simply return null on attempted
 * retrieval.
 */
public class Cache<T> {
	public Cache() {
		mCache = new HashMap<Integer, SoftReference<T>>();
	}
	/** Adds an object to the cache using its hash code. */
	public void put(T pObject) {
		put(pObject.hashCode(), pObject);
	}
	/** Adds an object to the cache. */
	public void put(int pIdentifier, T pObject) {
		mCache.put(pIdentifier, new SoftReference<T>(pObject));
	}
	/** Retrieves an object from the cache. */
	public T get(int pIdentifier) {
		SoftReference<T> reference = mCache.get(pIdentifier);
		
		return reference != null ? mCache.get(pIdentifier).get() : null;
	}

	private HashMap<Integer, SoftReference<T>> mCache;
}
